package hashbuck2;

public class HashBuck2<K, V> {

    static class Node<K, V> {
        private K key;
        private V val;
        private Node<K, V> next;

        public Node(K key, V val) {
            this.key = key;
            this.val = val;
        }

    }

    public Node<K, V>[] array;
    public int usedsize;

    public HashBuck2() {
        this.array = new Node[5];
    }

    public void put(K key, V val) {

        int index = key.hashCode() % array.length;
//        System.out.println(key.hashCode());
//        System.out.println(index);
        Node<K, V> cur = array[index];
        while (cur != null) {
            //这里比较的是key也就是两个对象的hashcode()，
            //person这个类重写了hashcode方法，并把id作为生成hashcode的唯一标准
            // hashcode()就是根据key这个自定义类型的成员变量得来的,它重写了hashcode方法
            //也就是说，如果这个条件成立，它们不一定是同一个对象，但是它们hashcode()的值相等
            //测试类里面p1和p2的id相同(认定为同一个人)，所以hashcode相同，也就是地址相同
            if (cur.key.equals(key)) {
                System.out.println(cur.key);
                System.out.println(key);

                System.out.println(-1);
                cur.val = val;
                return;
            }
            cur = cur.next;
        }

        Node<K, V> node = new Node<>(key, val);
        node.next = array[index];
        array[index] = node;
        usedsize++;

        if (loadFactor() >= 0.75) {
            //需要进行扩容散列表的长度
            resize();
        }
    }

    private void resize() {

        Node<K, V>[] tmparr = new Node[array.length * 2];

        for (int i = 0; i < array.length; i++) {
            Node<K, V> cur = array[i];
            while (cur != null) {
                Node<K, V> curNext = cur.next;
                int index = cur.key.hashCode() % tmparr.length;

                cur.next = tmparr[index];
                tmparr[index] = cur;

                cur = curNext;
            }
        }
        array = tmparr;
    }

    public V getValue(K key) {
        int index = key.hashCode() % array.length;
        Node<K, V> cur = array[index];
        while (cur != null) {
            if (cur.key.equals(key)) {
                return cur.val;
            }
            cur = cur.next;
        }
        return null;
    }

    //计算负载因子
    private double loadFactor() {
        return usedsize * 1.0 / array.length;
    }

}
